package myservlet.control;

import mybean.data.h1Tran_bean;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import static java.lang.Math.sqrt;

@WebServlet("/h1computeArea")
public class h1computeArea_servlet extends HttpServlet {
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        h1Tran_bean seriesData = new h1Tran_bean();  //创建Javabean对象
        request.setAttribute("seriesData", seriesData);//将seriesData存到request对象中
        String a_str = request.getParameter("a");
        String b_str = request.getParameter("b");
        String c_str = request.getParameter("c");

        //如果输入项为空会被重定向
        if (a_str.equals("") || b_str.equals("") || c_str.equals("")) {
            response.sendRedirect("/JSPOne_war_exploded/homework/week11/h1.jsp");
        } else {
            double a = Double.parseDouble(a_str);
            double b = Double.parseDouble(b_str);
            double c = Double.parseDouble(c_str);

            //如果边不是正数或者三边不构成三角形会被重定向
            if (a <= 0 || b <= 0 || c <= 0 || a + b < c || a + c < b || b + c < a) {
                response.sendRedirect("/JSPOne_war_exploded/homework/week11/h1.jsp");
            } else {
                seriesData.setB(b);
                seriesData.setC(c);
                double area = 0;
                double p = (a + b + c) / 2;
                area = sqrt(p * (p - a) * (p - b) * (p - c));
                seriesData.setArea(area);
                //请求example6_1_show.jsp显示seriesData中的数据:
                seriesData.setA(a);      //将数据存储在数据模型seriesData中
                RequestDispatcher dispatcher =
                        request.getRequestDispatcher("/homework/week11/h1_show.jsp");
                dispatcher.forward(request, response);
            }
        }
    }
}
